﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net;
using System.Text;

namespace PlanesManagerAPITestes
{
    [TestClass]
    public class UnitTest1
    {
        /// <summary>
        /// Devolve utilizadores
        /// </summary>
        [TestMethod]
        public void Capsulecrm_GetUsers()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);
            client.BaseAddress = new Uri("https://ua.capsulecrm.com/api/users");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync("").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                string dataObjects = response.Content.ReadAsStringAsync().Result;

            }
            else
            {
                Assert.Fail(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }  
        }

        /// <summary>
        /// Lista de utilizadores da aplicação
        /// </summary>
        [TestMethod]
        public void Capsulecrm_GetByQueryEmail()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);
            client.BaseAddress = new Uri("https://ua.capsulecrm.com/api/party?email=jhondoe@ua.pt");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            // List data response.
            HttpResponseMessage response = client.GetAsync("").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                string dataObjects = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                Assert.Fail(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }
        }

        /// <summary>
        /// Lista de utilizadores da aplicação
        /// </summary>
        [TestMethod]
        public void Capsulecrm_GetParty()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);
            client.BaseAddress = new Uri("https://ua.capsulecrm.com/api/party/");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            // List data response.
            HttpResponseMessage response = client.GetAsync("").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                string dataObjects = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                Assert.Fail(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }
        }

        /// <summary>
        /// Criar uma nove organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_AddCompany()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            var data = new StringContent("<organisation><name>Just a test company</name></organisation>", Encoding.UTF8, "text/xml"); 

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync("https://ua.capsulecrm.com/api/organisation", data).Result;
            
            response.EnsureSuccessStatusCode();
        }
        
        /// <summary>
        /// Update a uma organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_UpdateCompany()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            var data = new StringContent("<organisation><name></name></organisation>", Encoding.UTF8, "text/xml"); 

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PutAsync("https://ua.capsulecrm.com/api/organisation/60478742", data).Result;

            string dataObjects = response.Content.ReadAsStringAsync().Result;
            response.EnsureSuccessStatusCode();
        }

        /// <summary>
        /// Listar utilizadores e uma organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_UtilizadoresDeOrganizacao()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            // List data response.
            HttpResponseMessage response = client.GetAsync("https://ua.capsulecrm.com/api/party/57930949/people").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                string dataObjects = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                Assert.Fail(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
            }
        }

        /// <summary>
        /// Criar uma nove organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_AddPerson()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            string person = @"<person>
  <contacts>
    <email>
      <type>Home</type>
      <emailAddress>fake@fake.com</emailAddress>
    </email>
    <phone>
      <type>Mobile</type>
      <phoneNumber>321123312</phoneNumber>
    </phone>
  </contacts>
  <title>Mr</title>
  <firstName>Eric</firstName>
  <lastName>Schmidt</lastName>
  <about>A comment here</about>
</person>";
            var data = new StringContent(person, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync("https://ua.capsulecrm.com/api/person", data).Result;

            string dataObjects = response.Content.ReadAsStringAsync().Result;
            response.EnsureSuccessStatusCode();
        }

        /// <summary>
        /// Criar uma nove organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_AddOrganization()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            string telemovel = "1234567";
            string email = "fake@fake.com";
            string nomeEmpresa = "The Fake Company";

            string person = string.Format(@"<organisation>
              <contacts>
                <phone>
                  <type>Mobile</type>
                  <phoneNumber>{0}</phoneNumber>
                </phone>
                <email>
                  <type>Home</type>
                  <emailAddress>{1}</emailAddress>
                </email>
              </contacts>
              <name>{2}</name>
              <about></about>
            </organisation>", telemovel, email, nomeEmpresa);
            var data = new StringContent(person, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync("https://ua.capsulecrm.com/api/organisation", data).Result;

            response.EnsureSuccessStatusCode();
        }

        /// <summary>
        /// Criar uma nove organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_AddCase()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            string kase = @"<kase>
  <status>OPEN</status>
  <name>Website design</name>
  <description>Design and create website</description>
</kase>";
            var data = new StringContent(kase, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync("https://ua.capsulecrm.com/api/party/57930950/kase", data).Result;

            response.EnsureSuccessStatusCode();
        }

        /// <summary>
        /// Criar uma nove organização
        /// </summary>
        [TestMethod]
        public void Capsulecrm_GetIDByEmail()
        {
            string partyID = CRMLayer.CapsuleCRM.QueryPartyIDByEmail("jhondoe@ua.pt");

        }

        /// <summary>
        /// Criar uma nova opportunity
        /// </summary>
        [TestMethod]
        public void Capsulecrm_AddOpportunity()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("40eb1a3afd9ebadfd882210e8ea91a73", "x");

            HttpClient client = new HttpClient(handler);

            string opportunity = string.Format(@"<opportunity>
  <name>Flight Reservation</name>
  <description>Booking: {0} | Flight: {1} | Client Name: {2} | Client Document: {3} | Invoice: {4}</description>
  <currency>EUR</currency>
  <value>{5}</value>
  <durationBasis>DAY</durationBasis>
  <duration>1</duration>
  <expectedCloseDate>{6}</expectedCloseDate>
  <milestone>Won</milestone>
  <probability>100</probability>
</opportunity>", "123321", "2883", "José António", "0099898998", "abc213131", 1987, DateTime.Now.ToString());

            var data = new StringContent(opportunity, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync("https://ua.capsulecrm.com/api/party/58960269/opportunity", data).Result;

            response.EnsureSuccessStatusCode();
        }
    }
}
